import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score

# 设置全局字体为支持中文的字体（如 SimHei）
matplotlib.rcParams['font.family'] = 'SimHei'  # 黑体
matplotlib.rcParams['font.size'] = 12
matplotlib.rcParams['axes.unicode_minus'] = False  # 正确显示负号

# 加载糖尿病数据集
diabetes = load_diabetes()
print(diabetes.feature_names)

df_iris = pd.DataFrame(diabetes.data, columns=diabetes.feature_names)
df_iris['target'] = diabetes.target

dataX = df_iris.drop(columns=["target"]).values
dataY = df_iris['target'].values

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(dataX, dataY, test_size=0.2, random_state=42)

# 创建线性回归模型
model = LinearRegression()

# 训练模型
model.fit(X_train, y_train)

# 进行预测
y_pred = model.predict(X_test)

# 评估模型性能
mse = mean_squared_error(y_test, y_pred)  # 均方误差
r2 = r2_score(y_test, y_pred)  # R² 分数

print(f"均方误差 (MSE): {mse:.2f}")
print(f"R² 分数: {r2:.2f}")
print(model.intercept_)
print(model.get_params())
print(model.score(dataX,dataY))

# 可视化预测结果（以第一个特征为例）
plt.figure(figsize=(10, 6))
plt.scatter(X_test[:, 2], y_test, color='blue', label='实际值')  # 实际值
plt.scatter(X_test[:, 2], y_pred, color='red', label='预测值')  # 预测值
plt.xlabel(diabetes.feature_names[0])  # 第一个特征名称
plt.ylabel('病情指数')
plt.title('线性回归预测结果')
plt.legend()
plt.show()